package cn.edu.scau.cmi.duke.adapter;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class AdapterOfClassController  implements Initializable{
	@FXML
    private TableView<Student> studentTable;
	@FXML
    private TextField idField;
	@FXML
    private TextField nameField;
	
	 private ObservableList<Student> studentData = FXCollections.observableArrayList();
	 
	 private static List<Student> studentList = new ArrayList<>();
	 
	 AdapterOfClass classAdapter=new AdapterOfClass(); 
	 
	 @Override
	    public void initialize(URL location, ResourceBundle resources) {
	        initTable();
	    }
	 
	//表格初始化方法
	    private void initTable() {
	       studentTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);	     
	        showStudentData(studentList);
	    }
	    private void showStudentData(List<Student> studentList) {
	    	studentData.clear();
	        studentData.addAll(studentList);
	       studentTable.setItems(studentData);
	    }
     
	    public void addStudent() {
	    	 String idString =idField.getText().trim();
	    	 int id=Integer.parseInt( idString );
	    	 String name=nameField.getText().trim();
	    	 Student student=new Student();
	    	 student.setId(id);
	    	 student.setName(name);
	    	 if(isRepeat(student)) {
	    		 Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                 alert.setTitle("提示框");
                 alert.setContentText("学号"+student.getId()+"已存在!!!请重新输入");
                 Optional<ButtonType> result = alert.showAndWait();
	    	 }else {
	    	 
	    	 studentList .add(student);
	    	 studentList=classAdapter.sortStudent(studentList);
	    	 showStudentData(studentList);
	    	 }
	    }
	    
	   public boolean isRepeat(Student student) {
		       for(int i=0;i<studentList.size();i++) {
		    	   if(student.getId()==studentList.get(i).getId()) {
		    		   return true;
		    	   }
		       }
	   
	   return false;
	   }
}
